package com.hifar.test.structure.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.common.QueryParamBean;
import com.hifar.fw.utils.bean.BusiConst;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.log.AutoLogUtils;
import com.hifar.model.VO.ExportQueryParamsVO;
import com.hifar.model.VO.QueryParamsVO;
import com.hifar.plat.baseModal.pojo.BaseOssFiles;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.sys.BusiResponse;
import com.hifar.sys.MinioUtil;
import com.hifar.sys.PageResult;
import com.hifar.sys.SystemUtil;
import com.hifar.test.entrust.pojo.HfEnvEntrust;
import com.hifar.test.structure.pojo.HfEnvResPerson;
import com.hifar.test.structure.pojo.VO.HfEnvResPersonSaveVO;
import com.hifar.test.structure.service.IHfEnvResPersonService;
import com.hifar.test.structure.service.IHfEnvResPersonWorkRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhuWeiWei
 * @description 体系管理-人员档案
 * @date 2025/2/14 10:15
 */
@RestController
@RequestMapping("/api/busi/test/envResPerson")
@Api(tags = "体系管理-人员档案")
public class HfEnvResPersonController {
    @Autowired
    private IHfEnvResPersonService envResPersonService;
    @Autowired
    private IHfEnvResPersonWorkRecordService envResPersonWorkRecordService;
    @Autowired
    private AutoLogUtils autoLogUtils;

    @PostMapping("/add")
    @ApiOperation("新增")
    public BusiResponse add(@RequestBody @Validated HfEnvResPersonSaveVO hfEnvResPersonSaveVO) {
        envResPersonService.add(hfEnvResPersonSaveVO);
        autoLogUtils.addLog("环境试验-人员档案", String.format("新增人员档案:【%s】", hfEnvResPersonSaveVO.getIdName()));
        return BusiResponse.OK();
    }

    @PostMapping("/edit")
    @ApiOperation("编辑")
    public BusiResponse edit(@RequestBody @Validated HfEnvResPersonSaveVO hfEnvResPersonSaveVO) {
        envResPersonService.edit(hfEnvResPersonSaveVO);
        autoLogUtils.modifyLog("环境试验-人员档案", String.format("编辑人员档案:【%s】", hfEnvResPersonSaveVO.getIdName()));
        return BusiResponse.OK();
    }

    @ApiOperation("列表查询")
    @PostMapping("/listPage")
    public BusiResponse listPage(@RequestBody @Validated QueryParamsVO queryParamsVO) {
        QueryParamBean queryParamBean = new QueryParamBean<>(queryParamsVO);
        queryParamBean.addColumns(HfEnvResPerson.class);
        QueryWrapper queryWrapper = queryParamBean.getQueryWrapper();
        Page page = queryParamBean.getPage();
        Page pateData = envResPersonService.page(page, queryWrapper);
        PageResult pageResult = SystemUtil.parsePage(page, pateData);
        return BusiResponse.OK(pageResult);
    }


    @ApiOperation("删除")
    @PostMapping("/delete")
    public BusiResponse delete(@RequestBody List<String> idList) {
        List<HfEnvResPerson> delPersonList = envResPersonService.listByIds(idList);
        envResPersonService.removeByIds(idList);
        String delIdNames = delPersonList.stream()
                .map(HfEnvResPerson::getIdName)
                .collect(Collectors.joining(","));
        autoLogUtils.deleteLog("环境试验-人员档案", String.format("删除了人员档案:【%s】", delIdNames));
        return BusiResponse.OK();
    }

    @ApiOperation("查询详情")
    @GetMapping("/queryById")
    public BusiResponse queryById(@RequestParam("id") String id) {
        HfEnvResPerson envResPerson = envResPersonService.getById(id);
        Assert.notNull(envResPerson, "数据不存在!");
        HfEnvResPersonSaveVO hfEnvResPersonSaveVO = new HfEnvResPersonSaveVO();
        BeanUtils.copyProperties(envResPerson, hfEnvResPersonSaveVO);
     /*   List<HfEnvResPersonWorkRecord> workRecords = envResPersonWorkRecordService.listByPersonId(id);
        hfEnvResPersonSaveVO.setWorkRecordList(workRecords);*/

        List<BaseOssFiles> filesList = MinioUtil.listByRefId(id, "hf_env_res_person");
        List<BaseOssFiles> evaluateFilesList = MinioUtil.listByRefId(id, "hf_env_res_person_evaluate");
        hfEnvResPersonSaveVO.setFileInfoList(filesList);
        hfEnvResPersonSaveVO.setEvaluateFileList(evaluateFilesList);
        return BusiResponse.OK(hfEnvResPersonSaveVO);
    }



    @PostMapping("/exportExcel")
    @ApiOperation(value = "人员档案:导出数据")
    public Object exportExcel(@RequestBody ExportQueryParamsVO exportQueryParamsVO) {
        QueryParamBean queryParamBean = new QueryParamBean<>(exportQueryParamsVO);
        QueryWrapper<HfEnvResPerson> queryWrapper = queryParamBean.getQueryWrapper();
        BusiResponse export = envResPersonService.exportExcel(queryWrapper, exportQueryParamsVO.getOperationType());
        if (export.getCode() == BusiConst.CODE_SUCCESS) {
            String fileName;
            // 根据操作类型设置不同的文件名
            if (StringUtils.isNotBlank(exportQueryParamsVO.getOperationType()) && 
                exportQueryParamsVO.getOperationType().equals("template")) {
                fileName = "人员档案导入模板.xlsx";
            } else {
                String secretLevelText = StringUtils.trimNull(export.getExt("secretLevelText"), "非密");
                fileName = String.format("人员档案(%s).xlsx", secretLevelText);
            }

            String encode = null;
            try {
                encode = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "人员档案:导入excel数据")
    public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return BusiResponse.error("文件为空！");
        } else {
            if (ExcelTemplateUtil.isExcelFile(file)) {
                return envResPersonService.importExcel(file);
            } else {
                return BusiResponse.error("请上传excel文件！");
            }
        }
    }




}
